package com.it.reggie.Filter;

import com.alibaba.fastjson.JSON;
import com.it.reggie.common.BaseContext;
import com.it.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 过滤器：检查用户是否已经登录完成
 */


@WebFilter(filterName = "loginCheckFilter",urlPatterns = {"/*"})
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器 支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求URI
        String requestURI = request.getRequestURI();

        log.info("本次请求的URI {}",requestURI);

        //2.判断本次请求是否需要处理
            //2.1并不是所有请求需要处理  例如登录
        String[] string = new String[0];
        if (!requestURI.equals("/backend/index.html")) {
            string = new String[]{
                "/employee/login",
                "/employee/logout",
                "/employee/page",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"
            };
        }

        //2.2调用方法判断是否需要处理 返回值为true不需要处理
        boolean check = Check(string, requestURI);

        //3.如果不需要处理 直接放行
        if (check){
            log.info("本次请求{} 不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //4.判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("employee") != null){
            log.info("用户已登录 用户id {}",request.getSession().getAttribute("employee"));

            //获取id
            Long Id = (Long) request.getSession().getAttribute("employee");

            //设置值
            BaseContext.setCunrrenId(Id);

            filterChain.doFilter(request,response);
            return;
        } else if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录 用户id {}",request.getSession().getAttribute("user"));
            //获取id
            Long user = (Long) request.getSession().getAttribute("user");

            //写入线程
            BaseContext.setCunrrenId(user);

            //放行
            filterChain.doFilter(request, response);

            return;
        }

        log.info("用户未登录");
        //5.没有登录直接返回结果,通过输出流方式向客户端响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        return;
    }

    /**
     * 判断请求是否需要处理
     * @param urls 路径数组
     * @param requestURI 请求路径
     * @return 是否需要处理
     */
    public boolean Check(String[] urls, String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
